/*!
 * Copyright &copy; 2013-2015 山东易科德软件有限公司   All rights reserved.
 * 
 * 树列表公共方法
 * @author ThinkGem、刘保全
 * @version 2014-5-31
 */

/**
 * 获取所有跟节点ID
 */
function getTreetableRootIds(data){
	var ids = [], rootIds = [];
	for (var i=0; i<data.length; i++){
		ids.push(data[i].id);
	}
	ids = ',' + ids.join(',') + ',';
	for (var i=0; i<data.length; i++){
		if (ids.indexOf(','+data[i].parentId+',') == -1){
			if ((','+rootIds.join(',')+',').indexOf(','+data[i].parentId+',') == -1){
				rootIds.push(data[i].parentId);
			}
		}
	}
	return rootIds;
}

/**
 * 添加树列表行
 */
function addTreetableRow(tbodyObj, tpl, dataList, pid, isRoot, level, dict){
	for (var i = 0; i < dataList.length; i++){
		var row = dataList[i];
		if ((!row?'':!row.parentId?'':row.parentId) == pid){
			tbodyObj.append(Mustache.render(tpl, {
				dict: dict(row), pid: (isRoot ? 0 : pid), isRoot: isRoot, level: level+1, row: row
			}));
			addTreetableRow(tbodyObj, tpl, dataList, row.id, false, level+1, dict);
		}
	}
}

/**
 * 根据级别展开树
 * @param level 展开节点的级别，最小为1
 */
function expandTreetableByLevel(treeTable, level){
	for(var le=1; le<=level; le++){
		var lObj = jQuery('tr[level='+le+']', treeTable);
		for(var i=0;i<lObj.length;i++){
			var eId = lObj.eq(i).attr('data-tt-id');
			treeTable.treetable("expandNode", eId);
		}
	}
}

/**
 * 展开全部
 */
function expandAllTreetable(treeTable){
	loading();
	treeTable.treetable('expandAll');
	$(window).resize();
	closeLoading();
	return false;
}
/**
 * 折叠全部
 */
function collapseAllTreeTreetable(treeTable){
	loading();
	treeTable.treetable('collapseAll');
	$(window).resize();
	closeLoading();
	return false;
}

/**
 * AJAX 加载树表格
 */
function ajaxLoadTreetable(searchForm, treeTable, treeTableList, treeTableTpl,  
		addTreetableRowCallback, successCallback, isDefaultExpand, defaultExpandLevel){
	
	ajaxSubmitForm(searchForm, function(data){
		// 清除原数据
		if (treeTable){
			treeTable.treetable('destroy');
		}
//			if (dataTable){
//				dataTable.api().destroy();
//			}
		treeTableList.empty();
		
		// 加载新数据
		var rootIds = getTreetableRootIds(data);
		for (var i=0; i < rootIds.length; i++){
			addTreetableRow(treeTableList, treeTableTpl, data, rootIds[i], true, 0, function(row){
				return addTreetableRowCallback(row);
			});
		}
		
		// 初始化树结构表格
		treeTable.treetable({ expandable: true});
		
		// 默认展开节点
		if (isDefaultExpand == undefined ? true : isDefaultExpand){
			setTimeout(function(){
				expandTreetableByLevel(treeTable, defaultExpandLevel == undefined ? 1 : defaultExpandLevel);
			}, Metronic.isIE8() ? 500 : 0);
		}
		
//			// 初始化数据表格，可固定表格高度
//			dataTable = $('#treeTable').dataTable({
//				"scrollY": $.fn.dataTable.autoHeight($('#treeTable'))
//			});
		
//			// 窗体大小变化时自动调整数据表格高度
//			$.fn.dataTable.bindAutoHeight(dataTable);

		// 绑定展开或折叠节点，重绘数据表
		$('.indenter', treeTable).click(function(){
			$(window).resize();
		});
		
		// 加载成功回调
		successCallback();
	});
	return false;
}